package Cache;

import model.People;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: cyy
 **/
public class cache {


    public static void main(String[] args) {
        //测试查询
        testQuery();
    }



    private static void testQuery () {
        System.out.println("第一次查询开始");
        query();
        System.out.println("第一次查询结束");

        System.out.println("=============");

        System.out.println("第二次查询开始");
        query();
        System.out.println("第二次查询结束");
    }

    /*
     * 查询数据
     */
    private static List<People> query() {
        List<People> peopleList = null;

        List<People> cacheData = (List<People>) CacheSingletonUtil.getInstance().getCacheData(CacheSingletonUtil.PEOPLE_LIST_KEY);

        if (CollectionUtils.isNotEmpty(cacheData)) {
            System.out.println("从内存中读取");
            peopleList = cacheData;
        } else {
            System.out.println("从数据库中读取");
            peopleList = getData();
            // 添加到内存中
            CacheSingletonUtil.getInstance().addCacheData(CacheSingletonUtil.PEOPLE_LIST_KEY, peopleList);
        }

        for (People people : peopleList) {
            System.out.println("name : " + people.getName() + " age : " + people.getAge());
        }

        return peopleList;
    }

    /*
     * 删除数据
     */
    private void deleteCache () {
        CacheSingletonUtil.getInstance().removeCacheData(CacheSingletonUtil.PEOPLE_LIST_KEY);
    }

    private static List<People> getData() {
        People p1 = new People();
        p1.setName("Jack");
        p1.setAge(25);

        People p2 = new People();
        p2.setName("Brown");
        p2.setAge(28);

        List<People> peopleList = new ArrayList<>();
        peopleList.add(p1);
        peopleList.add(p2);

        return peopleList;
    }
}
